<template>
    <el-upload
      ref="upload"
      multiple
      action=""
      :http-request="handleUpload"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :limit="limit"
      :on-error="handleUploadError"
      name="file"
    >
        <slot></slot>
    </el-upload>
</template>

<script>
import OSS from 'ali-oss'
import { getOssInfo } from '@/request/api'
export default {
  props: {
    value: [String, Object, Array],
    // 数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 500,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      oss: null
    };
  },
  created() {
    this.initOSS()
  },
  methods: {
    async initOSS() {
      const res = await getOssInfo()
      if (res) {
        const { accessKey, accessSecret, bucket, endpoint } = res.data
        this.oss = new OSS({
          // 阿里云oss相关信息
          region: endpoint.split('.')[0],
          accessKeyId: accessKey,
          accessKeySecret: accessSecret,
          bucket: bucket
        })
      }
    },
    handleUpload(option) {
      const { file } = option
      const randomName = this.getFileNameUUID()
      const key = 'datarOSS/' + randomName + file.name // 设置上传路径
      const ossOptions = {
        headers: {
          'Content-Type': file.type,
          'Content-Disposition': 'inline'
        }
      }
      this.oss
        .put(key, file, ossOptions)
        .then((result) => {
          this.handleUploadSuccess(result.url, file)
        })
        .catch((error) => {
          // 上传失败的操作
          this.handleUploadError()
        })
    },
    getFileNameUUID() {
      function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
      }
      return `${+new Date()}_${rx()}${rx()}`
    },
    // 上传成功回调
    handleUploadSuccess(url, file) {
      this.$emit('success', {url, file})
      this.$refs.upload.clearFiles()
      this.$modal.closeLoading();
    },
     // 上传前校检格式和大小
     handleBeforeUpload(file) {
      const fileTypeList = this.fileType.map((v) => {
        return v.slice(1);
      });
      let isAble = false;

      fileTypeList.forEach((v) => {
        if (file.type.indexOf(v) > -1) {
          isAble = true;
        }
      });
      if (!isAble) {
        this.$modal.msgError(`请上传${fileType.join("/")}文件`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传，请稍候...");
      this.number++;
      return true;
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传失败，请重试");
      this.$modal.closeLoading();
    },
  },
};
</script>
<style scoped lang="less">
</style>
